import Vue from 'vue'
import VueRouter from 'vue-router'

// 导入组件，当项目运行时，就会全部导入
import MyLogin from '@/components/MyLogin'

Vue.use(VueRouter)


const router = new VueRouter({
  routes: [
    // 重定向，当访问 / 的时候转到 /home
    { path: '/', redirect: '/home' },
    { path: '/login', component: MyLogin },
    {
      path: '/home', component: () => import('@/components/MyHome.vue'),
      children: [
        { path: 'goods', component: () => import('@/components/menus/MyGoods.vue') },
        { path: 'orders', component: () => import('@/components/menus/MyOrders.vue') },
        { path: 'rights', component: () => import('@/components/menus/MyRights.vue') },
        { path: 'settings', component: () => import('@/components/menus/MySettings.vue') },
        { path: 'users', component: () => import('@/components/menus/MyUsers.vue') },
        {
          path: 'detail/:id',
          component: () => import('@/components/user/MyUserDetail.vue')
        },
      ]
    },
    { path: '*', component: () => import('@/components/NotFound.vue') }
  ],
  mode: 'history'  //指定使用历史模式的路由
})

// 添加路由前置守卫
router.beforeEach((to, from, next) => {
  // ${//to and from are Route Object,next() must be called to resolve the hook}
  // to 跳转到的路由 (to.path 表示即将跳转的路由地址)
  // from 从哪里来 表示上一个路由信息 ()
  // next() 是个函数  next() 表示通过 可以访问 
  // next(false) 表示不通过 
  // next('/login') 强制跳转到/login
  if (to.path === '/login') {
    next()  //跳转登录页 直接放行
  } else {
    if (localStorage.getItem('token')) {
      next()  //本地有token 登陆过 可放行
    } else {
      next('/login') //没有登录 强制跳转到/login
    }
  }
})

export default router
